using UnityEngine;
using System.Collections;

public class Attack : MonoBehaviour {
    public GameObject bullet;
    private CharacterController characterController;
    private GameObject player;
    private float offset = 1.5f;
    public float speed = 3;
    public float attackDistance = 12;
    public float coolDown = 2;
    private float attackTimer = 0;
    
	void Start () {
        player = GameObject.FindGameObjectWithTag("Player");
        characterController = GetComponent<CharacterController>();
	}
	
	
	void Update () {
        Follow();
        if (IsPlayerInAttackDistance())
        {
            if (attackTimer > 0)
            {
                attackTimer -= Time.deltaTime;
            }
            else
            {
                attackTimer = 0;
            }

            if (attackTimer == 0)
            {
                AttackPlayer();
                attackTimer = coolDown;
            }
        }
	}

    private void Follow()
    {
        transform.LookAt(player.transform.position);
        if (Vector3.Distance(player.transform.position, transform.position) > offset)
        {
            Vector3 direction = transform.TransformDirection(Vector3.forward * speed);
            characterController.SimpleMove(direction);
        }
    }

    private bool IsPlayerInAttackDistance()
    {
        Vector3 dir = (player.transform.position - transform.position).normalized;
        float direction = Vector3.Dot(dir, transform.forward);
        float distance = Vector3.Distance(player.transform.position, transform.position);

        if (distance < attackDistance && direction > 0)
        {
            return true;   
        }
        return false;
    }

    private void AttackPlayer()
    {
        GameObject bulletObj = Object.Instantiate(bullet, gameObject.transform.position, Quaternion.identity) as GameObject;
        Bullet bulletScript = bulletObj.GetComponent<Bullet>();
        bulletScript.SetTarget(player.transform.position);
    }
}
